package com.qinglei.recoup.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.domain.Tree;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.domain.RadarBed;
import com.qinglei.recoup.system.domain.Room;
import com.qinglei.recoup.system.domain.User;
import com.qinglei.recoup.system.pojo.*;
import com.qinglei.recoup.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;

@Api(tags = "床位相关控制器-张 已实现")
@Slf4j
@Validated
@RestController
@RequestMapping("bed")
public class BedController {

    @Autowired
    private BedService bedService;

    @Autowired
    private BuildingService buildingService;

    @Autowired
    private FloorService floorService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private RadarBedService radarBedService;

    @Autowired
    private MonitorTimeService monitorTimeService;

    @Resource
    private RadarUserDataService radarUserDataService;

    @Autowired
    private NurseBedService nurseBedService;

    @Autowired
    private BedMonitorTimeService bedMonitorTimeService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private RadarUserDataFourService radarUserDataFourService;

    @ApiOperation(value = "护工和院长首页 获取床位列表接口-石-已完成")
    @GetMapping("/showList")
    public CommonRes<List<BedStatusVO>> getBedShowList() {
        User currentUser = RecoupUtil.getCurrentUser();
        Long userId = currentUser.getId();
        Integer roleId = Integer.parseInt(currentUser.getRoleId());
        List<BedStatusVO> list = bedService.getBedShowListByUser(userId, roleId);

        return CommonRes.ok(list);
    }

    @ApiOperation(value = "护工和院长实时监控页面 获取床位实时监测数据-已完成")
    @ApiImplicitParam(name = "bedId", value = "床位ID", paramType = "query", dataType = "Integer", required = true)
    @GetMapping("/realTimeData")
    public CommonRes getRealTimeData(@NotNull(message = "{required}") Integer bedId,Integer second ) throws RedisConnectException {

        Bed bed = bedService.getById(bedId);
        if(bed == null ){
            return CommonRes.failed("床位不存在");
        }

        if(StringUtils.isEmpty(bed.getRadarVersion())){
            return CommonRes.failed("暂时收不到数据，请尝试重新连接电源并且配网");
        }
        Integer tenantId = RecoupUtil.getCurrentUser().getTenantId();
        if (bed.getRadarVersion().equals("3_0")) {
            RealTimeDataVO realTimeDataVO = radarUserDataService.getRealTimeData(bedId);
            if (realTimeDataVO == null) {
                return CommonRes.failed("床位或者设备信息不存在");
            }
            return CommonRes.ok(realTimeDataVO);
        } else if (bed.getRadarVersion().equals("4_0")) {
            RealTimeDataVOV4 realTimeDataVOV4 = radarUserDataFourService.getRealTimeData(bedId, second, tenantId);
            if (realTimeDataVOV4 == null) {
                return CommonRes.failed("床位或者设备信息不存在");
            }
            return CommonRes.ok(realTimeDataVOV4);
        }

        return null;
    }

    @ApiOperation(value = "护工人员配置页面 获取床位树形列表-已完成 id,key(同id),title,type(1-床位)，value（床位数量）")
    @ApiImplicitParam(name = "userId", value = "护工ID", paramType = "query", dataType = "int", required = false)
    @GetMapping("/treeList")
    public CommonRes<Tree<Bed>> getBedTree4Nurse(Long userId) {
        Tree<Bed> bedTreeList = nurseBedService.getBedTree4Nurse(userId);
        return CommonRes.ok(bedTreeList);
    }

    @ApiOperation(value = "分页查询床")
    @GetMapping("/showPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间id", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页码，从1开始，默认是1", paramType = "query", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页条数，默认20", paramType = "query", dataType = "Integer")
    })
    public CommonRes<IPage<BedShowVO>> showPageBed(BedPageParam bedPageParam) {
        return bedService.showPageBed(bedPageParam);
    }

    @ApiOperation(value = "添加床")
    @PostMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间id", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "floorId", value = "层id", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "buildingId", value = "楼id", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "name", value = "床名称", paramType = "body", dataType = "String", required = true)})
    @Transactional(rollbackFor = Exception.class)
    public CommonRes addBed(@RequestBody AddBedParam addBedParam) throws RedisConnectException {
        //查询房间中是否有该名称的床位
        Integer selectCount = bedService.getBaseMapper().selectCount(Wrappers.<Bed>lambdaQuery()
                .eq(Bed::getRoomId, addBedParam.getRoomId())
                .eq(Bed::getName, addBedParam.getName()));
        if (selectCount > 0) {
            return CommonRes.failed("房间中已经存在此床位名称");
        }
        Bed bed = new Bed();
        BeanUtils.copyProperties(addBedParam, bed);
        Room room = roomService.getBaseMapper().selectById(addBedParam.getRoomId());
        //离床时间阈值
        bed.setOutBedTimeout(room.getOutBedTimeout());
        int count = bedService.getBaseMapper().insert(bed);
        if (count > 0) {
            //获取上层检测时间设置
            List<TimePeriodParam> monitorTimeList = monitorTimeService.getMonitorTimeByObjIdAndType(addBedParam.getRoomId(), BedService.TYPE_ROOM);
            if (CollectionUtils.isEmpty(monitorTimeList)) {
                //添加默认检测时间
                monitorTimeList = systemConfigService.getDefaultMonitorTime();
            }
            bedMonitorTimeService.syncMonitorTimes(monitorTimeList, bed.getId());
            buildingService.addBedCnt(bed.getBuildingId());
            floorService.addBedCnt(bed.getFloorId());
            roomService.addBedCnt(bed.getRoomId());
            return CommonRes.ok();
        }
        return CommonRes.failed("新增床失败");
    }

    @ApiOperation(value = "通过床id查询床")
    @GetMapping("/{id}")
    @ApiImplicitParam(name = "id", value = "床id", paramType = "path", dataType = "Integer")
    public CommonRes<BedShowVO> getBedById(@PathVariable Integer id) {
        Bed bed = bedService.getBaseMapper().selectById(id);
        BedShowVO bedShowVO = new BedShowVO();
        BeanUtils.copyProperties(bed, bedShowVO);
        return CommonRes.ok(bedShowVO);
    }

    @ApiOperation(value = "修改床信息")
    @PutMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "床id", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "name", value = "床名称", paramType = "body", dataType = "String", required = true)})
    public CommonRes addRadar(@RequestBody BedShowVO bedShowVO) {
        Bed bed1 = bedService.getBaseMapper().selectById(bedShowVO.getId());
        Integer selectCount = bedService.getBaseMapper().selectCount(Wrappers.<Bed>lambdaQuery()
                .eq(Bed::getRoomId, bed1.getRoomId())
                .eq(Bed::getName, bedShowVO.getName()));
        if (selectCount > 0) {
            return CommonRes.failed("房间中已经存在此床位名称");
        }
        Bed bed = new Bed();
        BeanUtils.copyProperties(bedShowVO, bed);
        int count = bedService.getBaseMapper().updateById(bed);
        if (count > 0) {
            return CommonRes.ok();
        }
        return CommonRes.failed("修改床信息失败");
    }

    @ApiOperation(value = "通过床id删除床")
    @DeleteMapping("/{id}")
    @ApiImplicitParam(name = "id", value = "床id", paramType = "path", dataType = "Integer", required = true)
    public CommonRes delBedById(@PathVariable Integer id) {
        Integer num = radarBedService.getBaseMapper().selectCount(Wrappers.<RadarBed>lambdaQuery().eq(RadarBed::getBedId, id));
        if (num > 0) {
            return CommonRes.failed("当前床位已绑定监测仪，请解绑后再删除");
        }
        Bed bed = bedService.getBaseMapper().selectById(id);
        int count = bedService.getBaseMapper().deleteById(id);
        if (count > 0) {
            buildingService.subBedCnt(bed.getBuildingId(), 1);
            floorService.subBedCnt(bed.getFloorId(), 1);
            roomService.subBedCnt(bed.getRoomId());
            return CommonRes.ok();
        }
        return CommonRes.failed("删除床信息失败");
    }

    @ApiOperation(value = "管理员端监测仪与床位配置 获取床位树形列表(床位是否可用)-已完成 id,title,type(1-床位)，value（床位数量）")
    @GetMapping("/bedTree")
    public CommonRes<Tree<Bed>> getBedTree4BindRadar() {
        Tree<Bed> tree4BindRadar = radarBedService.getBedTree4BindRadar();
        return CommonRes.ok(tree4BindRadar);
    }

    @ApiOperation(value = "院长端 历史信息筛选 所有床位列表-已完成")
    @GetMapping("/nameList")
    public CommonRes<List<BedVO>> getBedNameList() {
        List<BedVO> bedList = bedService.getBedNameList();
        return CommonRes.ok(bedList);
    }

    @ApiOperation(value = "[2.0新增]更新用户情况备注")
    @PutMapping("/userRemarks")
    public CommonRes<Object> updateUserRemarks(@RequestBody BedRemarksParam param) {
        Bed bed = bedService.getById(param.getBedId());
        if (bed == null) {
            return CommonRes.failed("床位不存在");
        }
        Bed bedUpdate = new Bed();
        bedUpdate.setId(bed.getId());
        bedUpdate.setUserRemarks(param.getRemarks());
        bedService.updateById(bedUpdate);
        return CommonRes.ok();
    }

    @Autowired
    private UserService userService;
    @GetMapping("/getAllBeds")
    public CommonRes<Object> getAllBeds(String mobile){
            if (StringUtils.isEmpty(mobile)){
                return CommonRes.failed("手机号不能为空！");
            }
            mobile=mobile.trim();
            User user = userService.findByMobile(mobile);
            if(user == null){
                return CommonRes.failed("手机号："+mobile+"未绑定账户");
            }
            Long userId = user.getId();
            Integer roleId = Integer.parseInt(user.getRoleId());
            Integer tenantId = user.getTenantId();
            List<BedStatusVO> list = bedService.getAllBeds(userId, roleId,tenantId);
            return CommonRes.ok(list);
    }


}
